/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[RefererTag.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package jsp.tag.cases;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * 防盗链标签
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class RefererTag extends SimpleTagSupport {

	private String website; // 网站域名
	private String redirectPage; // 要跳转的页面

	public void setWebsite(String website) {
		this.website = website;
	}

	public void setRedirectPage(String redirectPage) {
		this.redirectPage = redirectPage;
	}

	@Override
	public void doTag() throws JspException, IOException {
		PageContext pageContext = (PageContext) this.getJspContext();
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

		// 获取请求的来路
		String referer = request.getHeader("referer");
		System.out.println("referer " + referer);
		// 如果访问来路不是指定的website, 则重定向到指定的page
		if (referer == null || !referer.startsWith(website)) {
			HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
			String webContent = request.getContextPath();
			if (redirectPage.startsWith(webContent)) {
				response.sendRedirect(redirectPage);
			} else {
				response.sendRedirect(webContent + redirectPage);
			}

			// 重定向后, 控制保护的页面不被执行
			throw new SkipPageException();
		}
	}
}
